//
//  URLProtocolHandler.m
//  ZLZKBaseUtils
//
//  Created by sxh on 2021/4/11.
//

#import "URLProtocolHandler.h"
@interface URLProtocolHandler()

@property (nonatomic, strong) NSBundle *mainBundle;

@end

@implementation URLProtocolHandler

+ (instancetype)shared {
    static URLProtocolHandler *shared;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        shared = [[URLProtocolHandler alloc] init];
    });
    return shared;
}

- (void)setConfigure:(NSString *)configPath {
    
    _mainBundle = [NSBundle bundleWithPath:configPath];
}

- (NSBundle *)bundle {
    
    return self.mainBundle;
}

- (NSDictionary *)configure {
    NSData *data = [NSData dataWithContentsOfFile:[[self bundle] pathForResource:@"protocol" ofType:@"json"]];
    NSDictionary *configure = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions | NSJSONWritingPrettyPrinted error:nil];
    return configure;
}

//获取资源bundle
- (NSBundle *)getSourceBundle {
    
    NSString *mainStr = [[NSBundle mainBundle] bundlePath];
    
    NSString *moduleStr1 = [mainStr stringByAppendingPathComponent:@"ZLZKBaseUtils.bundle"];
    NSBundle *module1 = [NSBundle bundleWithPath:moduleStr1];
    
    NSString *moduleStr2 = [mainStr stringByAppendingPathComponent:@"Frameworks/ZLZKBaseUtils.framework/ZLZKBaseUtils.bundle"];
    NSBundle *module2 = [NSBundle bundleWithPath:moduleStr2];
    return module1 ?: module2;
}

- (NSBundle *)mainBundle {
    if (!_mainBundle) {
        _mainBundle = [self getSourceBundle];
    }
    return _mainBundle;
}

@end
